import { memo, useEffect, useState, useRef } from 'react'
import styles from './index.module.scss'
import QuestionCard from '@/components/QuestionCard'
import { useTitle, useDebounceFn, useRequest } from 'ahooks'
import { Typography, Spin } from 'antd'
import ListSearch from '@/components/ListSearch'
import { questionListItemType } from '@/types'
import { useSearchParams } from 'react-router-dom'
import { api_getQuestionList } from '@/api'

const List = memo(() => {
  useTitle('我的问卷')
  const { Title } = Typography

  const [page, setPage] = useState(1)
  const [list, setList] = useState<questionListItemType[]>([])
  const [total, setTotal] = useState(0)

  const hasMore = total > list.length && list.length > 0
  const [searchParams] = useSearchParams()
  const keyword = searchParams.get('keyword') || ''

  const footRef = useRef<HTMLDivElement>(null)

  const { run: loadMore, loading } = useRequest(
    async () => {
      const res = await api_getQuestionList({ page, keyword })
      setList(list => [...list, ...res.list])
      setTotal(res.total)
    },
    {
      manual: true,
      onSuccess: () => {
        setPage(page => page + 1)
      },
    }
  )

  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const ele = footRef.current
      if (ele && ele.getBoundingClientRect().top < window.innerHeight) {
        loadMore()
      }
    },
    { wait: 1000 }
  )

  useEffect(() => {
    tryLoadMore()
  }, [list])

  useEffect(() => {
    if (!hasMore) return
    window.addEventListener('scroll', tryLoadMore)
    return () => {
      window.removeEventListener('scroll', tryLoadMore)
    }
  }, [hasMore])

  useEffect(() => {
    setList([])
    setPage(1)
    tryLoadMore()
  }, [searchParams])

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {list.map((q: questionListItemType) => (
          <QuestionCard key={q._id} {...q} />
        ))}
      </div>
      <div className={styles.footer} ref={footRef}>
        {loading || hasMore ? (
          <div style={{ textAlign: 'center' }}>
            <Spin size="large" />
          </div>
        ) : (
          <span>已经到底了~</span>
        )}
      </div>
    </>
  )
})

export default List
